<template>
  <view>
    <!-- <base-container style="padding: 0!important;" :style="style" :contentViewStyle='style'> -->
    <view>
      <view style="background-color: #f7f7f7;">
        <base-card>
          <template #title>
            <view style="display: flex;padding: 5rpx">
              <view style="flex: 1">
                <text
                    style="font-size: 34rpx; color: #333; font-weight: bold;">{{ form.mdcInstitutionShortName }}
                </text>
                <uni-tag :text="form.mdcInstitutionType + '类'"
                         custom-style="background-color: #e6eeff; border-color: #e6eeff; color: #2c70fc;line-height: 1; padding: 1px 7px; margin-left: 10rpx"
                         type="primary"/>
              </view>
              <view style="font-size: 26rpx; color: #999999">
                {{ form.createTime || nowTime }}
              </view>
            </view>
          </template>
          <u-gap height="10"></u-gap>
          <view>
            <view class="cell-lx">
              <text class="hd">机构名称</text>
              <text class="bd">{{ form.mdcInstitutionName }}</text>
            </view>
            <view class='cell-lx'>
              <text class="hd">机构地址</text>
              <text class="bd">{{ form.mdcInstitutionAddress }}</text>
            </view>
            <view class="cell-lx">
              <text class="hd">当前定位</text>
              <text class="bd">{{ location.address }}</text>
            </view>
            <view class="cell-lx">
              <text class="hd">电子围栏</text>
              <text class="bd">{{ form.electronicFence }}米</text>
            </view>
          </view>
        </base-card>
        <!-- <u-gap height="10"></u-gap> -->
        <uni-forms ref="form" :border="true" :model="form" label-width="150">
          <uni-card :border="false" :isShadow="false" is-full title="感染性医疗废物(KG)(841-001-01)">
            <uni-forms-item label="桶数" name="infectionBarrelsCount">
              <uni-easyinput v-model="form.infectionBarrelsCount" :input-border="false" placeholder="请输入"
                             type="number">
                <template #right>桶</template>
              </uni-easyinput>
            </uni-forms-item>
            <uni-forms-item label="毛重" name="infectionGrossWeight">
              <uni-easyinput v-model="form.infectionGrossWeight" :input-border="false" placeholder="请输入"
                             type="digit">
                <template #right>kg</template>
              </uni-easyinput>
            </uni-forms-item>
            <uni-forms-item label="净重" name="infectionNetWeight" required
                            :rules="[{ required: true, errorMessage: '不能为空' }]">
              <uni-easyinput v-model="form.infectionNetWeight" @change="staticWeight(form)"
                             :input-border="false" placeholder="请输入" type="digit">
                <template #right>
                  <text style="margin-left: 10rox; font-size: 32rpx;">kg</text>
                </template>
              </uni-easyinput>
            </uni-forms-item>
          </uni-card>
          <u-gap height="10"></u-gap>
          <uni-card :border="false" :isShadow="false" is-full title="损伤性医疗废物(KG)(841-002-01)">
            <uni-forms-item label="桶数" name="sharpsBarrelsCount">
              <uni-easyinput v-model="form.sharpsBarrelsCount" :input-border="false" placeholder="请输入" type="number">
                <template #right>桶</template>
              </uni-easyinput>
            </uni-forms-item>
            <uni-forms-item label="毛重" name="sharpsGrossWeight">
              <uni-easyinput v-model="form.sharpsGrossWeight" :input-border="false" placeholder="请输入" type="digit">
                <template #right>kg</template>
              </uni-easyinput>
            </uni-forms-item>
            <uni-forms-item label="净重" name="sharpsNetWeight" required
                            :rules="[{ required: true, errorMessage: '不能为空' }]">
              <uni-easyinput v-model="form.sharpsNetWeight" @change="staticWeight(form)"
                             :input-border="false" placeholder="请输入" type="digit">
                <template #right>kg</template>
              </uni-easyinput>
            </uni-forms-item>
          </uni-card>
          <u-gap height="10"></u-gap>
          <uni-card :border="false" :isShadow="false" is-full title="合计">
            <uni-forms-item :rules="[{ required: true, errorMessage: '不能为空' }]" label="合计（净重）"
                            name="totalWasteNetWeight" required>
              <uni-easyinput v-model="form.totalWasteNetWeight" :input-border="false" placeholder="请输入" type="digit"
                             @change="revisedWeightChange(form)">
                <template #right>kg</template>
              </uni-easyinput>
              <p style="width: 100%; text-align: right; font-size: .8em; color: #d9d9d9">每个空桶重4.3kg</p>
            </uni-forms-item>
            <uni-forms-item label="交接人签字" name="transferPerson">
              <uni-easyinput v-model="form.transferPerson" :input-border="false"
                             :styles="{ disableColor: '#fff', color: '#666666'}"
                             disabled placeholder="请输入">
              </uni-easyinput>
            </uni-forms-item>
          </uni-card>
          <u-gap height="10"></u-gap>
          <uni-card :border="false" :isShadow="false" is-full title="收运信息">
            <uni-forms-item :rules="[{ required: true, errorMessage: '不能为空'}]" label="接收时间" name="receivingTime"
                            required>
              <uni-datetime-picker v-model="form.receivingTime" :border="false" :clear-icon="false"
                                   :input-border="false" type="datetime"/>
            </uni-forms-item>
            <uni-forms-item :rules="[{ required: true, errorMessage: '不能为空' }]" label="是否属实" name="truthfulness"
                            required>
              <base-picker v-model="form.truthfulness" :localdata="[{text: '是', value: 'Y'},{text: '否', value: 'N'}]"
                           @change="revisedWeightChange(form)"/>
            </uni-forms-item>
            <uni-forms-item :rules="[{ required: true, errorMessage: '不能为空' }]" label="复核重量"
                            name="revisedWeight"
                            required>
              <uni-easyinput v-model="form.revisedWeight" :disabled="form.truthfulness == 'Y'" :input-border="false"
                             :styles="{ disableColor: '#fff', color: '#666666'}" placeholder="请输入" type="digit">
                <template #right>kg</template>
              </uni-easyinput>
            </uni-forms-item>
            <uni-forms-item :rules="[{ required: true, errorMessage: '不能为空' }]" label="收运人签字"
                            name="collectionTransportPerson" required>
              <uni-easyinput v-model="form.collectionTransportPerson" :input-border="false"
                             :styles="{ disableColor: '#fff', color: '#666666'}" disabled
                             placeholder="请输入">
              </uni-easyinput>
            </uni-forms-item>
            <uni-forms-item :rules="[{ required: true, errorMessage: '不能为空' }]" label="车牌号" name="vehicleId"
                            required>
              <base-picker v-model="form.vehicleId" :localdata="vehicleList"/>
            </uni-forms-item>
            <uni-forms-item :rules="[{ required: true, errorMessage: '不能为空' }]" label="驾驶员" name="driverId"
                            required>
              <base-picker v-model="form.driverId" :localdata="driverList"/>
            </uni-forms-item>
            <uni-forms-item label="装卸员" name="loUnPersonId">
              <base-picker v-model="form.loUnPersonId" :localdata="loUnPersonnelList"/>
            </uni-forms-item>
            <uni-forms-item label="异常备注" name="abnormalRemark">
              <uni-easyinput v-model="form.abnormalRemark" :input-border="false" maxlength="400" placeholder="请输入"
                             type="textarea"/>
            </uni-forms-item>
            <uni-forms-item label-width="0" name="collectionTransportPlanPic">
              <base-images v-model="form.collectionTransportPlanPic" title="收运记录单照片"/>
            </uni-forms-item>
          </uni-card>
        </uni-forms>
      </view>
      <!-- <template #actions> -->
      <view class="foot-Btn" style="background-color: #f7f7f7;">
        <view class="btn" @click="submit">提交</view>
      </view>
      <!-- <button class="main-btn" type="primary" @click="submit">提交</button> -->
      <!-- </template> -->
    </view>
    <!-- </base-container> -->
  </view>
</template>

<script>
import {TaskPlanApi as Api} from "@/comms/api/taskPlanApi";
import {DateUtil, getUserInfo, getUserName, LocationUtils, Msg, toBack} from "@/utils/BaseUtils";

export default {
  data() {
    return {
      params: {},
      form: {
        receivingTime: "",
      },
      location: {},
      nowTime: DateUtil.getCurrDateTime(),
      driverList: [],
      loUnPersonnelList: [],
      vehicleList: [],
      style: {
        'background-color': '#f7f7f7'
      }
    };
  },
  onLoad(params) {
    this.params = params;
  },
  mounted() {
    this.loadDate(this.params)
  },
  methods: {
    async loadDate({
                     taskPlanId,
                     mdcInstitutionId
                   }) {
      Msg.loading(async close => {
        await Promise.all([
          Api.taskPlanVehicleList({
            taskPlanId
          }).then(({
                     data
                   }) => {
            this.vehicleList = (data || []).map(val => ({
              value: val.vehicleId,
              text: val.licensePlate
            }))
          }),
          Api.taskPlanDriverList({
            taskPlanId
          }).then(({
                     data
                   }) => {
            this.driverList = (data || []).map(val => ({
              value: val.ctPersonId,
              text: val.personName
            }))
          }),
          Api.taskLoUnPersonnelList({
            taskPlanId
          }).then(({
                     data
                   }) => {
            this.loUnPersonnelList = (data || []).map(val => ({
              value: val.ctPersonId,
              text: val.personName
            }))
          }),
        ]);
        if (taskPlanId && mdcInstitutionId) {
          await Api.medicalWasteTransferDetail({
            taskPlanId,
            mdcInstitutionId
          }).then(({data}) => {
            this.form = {
              ...data
            }
          })
        }
        this.form.collectionTransportPerson = getUserName();
        this.form.driverId = this.form.driverId ? this.form.driverId : getUserInfo()?.userId;
        this.form.receivingTime = this.form.receivingTime || DateUtil.getCurrDateTime()
        this.form.truthfulness = this.form.truthfulness ? this.form.truthfulness : "Y";
        this.revisedWeightChange(this.form)

        try {
          const location = await LocationUtils.getLocation();
          console.log('当前位置信息：', location);
          this.location = location;
        } catch (error) {
          Msg.error("获取定位信息时出错")
          console.error('获取定位信息时出错：', error);
        }
        close?.();
      })
    },

    submit() {
      Msg.loading(close => {
        const {
          form = {}, location = {}
        } = this;
        // 计算是否在电子围栏内
        // if (form.electronicFence > 0) {
        //   const distance = GeoUtils.calculateDistance({
        //         lat: form.mdcInstitutionLatitude,
        //         lon: form.mdcInstitutionLongitude
        //       },
        //       {lat: location.latitude, lon: location.longitude});
        //   if (distance > (form.enclosure * 1.3)) {
        //     close?.();
        //     return Msg.error("您不在围栏区间内")
        //   }
        // }

        this.$refs.form.validate().then(async (valid) => {
          Msg.confirm("确认收运吗？").then(() => {
            Api.receiveAdd(this.convert())
                .then(res => {
                  Msg.success("保存成功")
                  uni.$emit('plannedRouterReload')
                  uni.$emit('taskIndexReload')
                  setTimeout(() => toBack?.(), 1000)
                }).finally(() => close?.())
          }).catch(() => close?.())
        }).catch(() => close?.())
      })
    },
    revisedWeightChange(form = {}) {
      if (form.truthfulness == 'Y') {
        form.revisedWeight = form.totalWasteNetWeight
      }
    },
    staticWeight(form = {}) {
      form.totalWasteNetWeight = Number(form.infectionNetWeight || 0) + Number(form.sharpsNetWeight || 0);
      form.totalWasteNetWeight = (form.totalWasteNetWeight||0).toFixed(2);
      this.revisedWeightChange(form)
    },
    convert() {
      const {
        form = {}, vehicleList = [], itemList = []
      } = this;
      return {

        "id": form.id,
        "taskPlanId": form.taskPlanId,
        "mdcInstitutionId": form.mdcInstitutionId,

        "infectionBarrelsCount": form.infectionBarrelsCount,
        "infectionGrossWeight": form.infectionGrossWeight,
        "infectionNetWeight": form.infectionNetWeight,

        "sharpsBarrelsCount": form.sharpsBarrelsCount,
        "sharpsGrossWeight": form.sharpsGrossWeight,
        "sharpsNetWeight": form.sharpsNetWeight,

        "totalWasteNetWeight": form.totalWasteNetWeight,
        "transferPerson": form.transferPerson,

        "receivingTime": form.receivingTime,
        "truthfulness": form.truthfulness,
        "revisedWeight": form.revisedWeight,
        "collectionTransportPerson": form.collectionTransportPerson,
        "vehicleId": form.vehicleId,
        "driverId": form.driverId,
        "loUnPersonId": form.loUnPersonId,
        "abnormalRemark": form.abnormalRemark,
        "collectionTransportPlanPic": form.collectionTransportPlanPic,
        "transferPersonMobile": form.transferPersonMobile,

        longitude: this.location.longitude,
        latitude: this.location.latitude,
      }
    }
  }
}
</script>
<style>
page {
  background: #f7f7f7 !important;
}
</style>
<style lang="scss">
.uni-card {
  margin-bottom: 15rpx;
}

v-deep .uni-forms-item__label {
  font-size: 40rpx !important;
}

v-deep .uni-card--full {
  margin-top: 20rpx !important;
}
</style>
